package com.phy.mail.servlets;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.RandomAccessFile;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Random;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.log4j.Logger;
import com.phy.core.AchieveSys;
import com.phy.core.OutPut;
import com.phy.core.Regex;
import com.phy.core.StringToArray;

/**
 * Servlet implementation class Domains
 */
public class Domains extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private static Logger logger = Logger.getLogger(Domains.class.getClass());

	public void init(ServletConfig config) throws ServletException {

	}

	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// 发送变量，统计第几次请求
		long startTime = System.currentTimeMillis();
		String dns = (String) request.getParameter("domain");
		String id = (String) request.getParameter("id");
		// 第几次响应
		String tjs = (String) request.getParameter("tj");
		// 取得这个请求将要响应的次数
		String trans = (String) request.getParameter("tran");
		String addr= (String) request.getParameter("address");
		int tj = Integer.parseInt(tjs);
		int tran = Integer.parseInt(trans);
		/*System.out.println("您输入的域名是:" + dns);
		System.out.println("header信息" + request.getHeader("Content-length")
				+ "bytes");
		System.out.println("当前id是:" + id);*/
		// 提取以空格为分隔符的字符串，将其插入数组。
		String[] strArray = StringToArray.convertStrToArray(dns);
		// 使用该组dns列表中的一个，逐一查找
		// 域名、mx记录、使用的邮件系统、邮件系统信息返回值
		
		// 提取有效域名
		ArrayList<?> EffectDomainList = null;
		Regex regex = new Regex();
		EffectDomainList = regex.ExtractDNS(strArray);
		AchieveSys sys = new AchieveSys();
		// 看看有几个有效的域名
		int domainLength = EffectDomainList.size();
		
		System.out.println("有" + domainLength + "个有效域名");
		String filein = "";
		String EmailSystemShortName = ""; // 使用的邮件系统
		OutPut outPut=new OutPut();
		
		// 创建输出流对象
		PrintWriter out = response.getWriter();
		// 设置输出信息的格式及字符集
		response.setContentType("text/xml; charset=UTF-8");
		response.setHeader("Cache-Control", "no-cache");
		out.println("<response>");
		// 取得优先级最高的mx记录
		for (int L = 0; L < domainLength; L++) {
			String domain = EffectDomainList.get(L).toString().trim();// 查询的域名
			String BestMX =outPut.getBestMX(domainLength, sys, domain); // 优先级最高的 mx记录
			out.println("<dns>" + domain + "</dns>");
			if(sys.checkARecord(BestMX)){
				String[] opArr=outPut.DealLogic(domainLength,sys,domain,BestMX);
				out.println("<mx>" + opArr[0] + "</mx>");
				out.println("<info>" + regex.StrChange(opArr[2]) + "</info>");
				out.println("<shortname>" + opArr[1] + "</shortname>");
				EmailSystemShortName=opArr[1];
			}
			else{
				//域名前添加mail/pop/pop3/smtp连25端口，mail连110端口
				//String info=sys.SocketValue("mail."+domain, 110, 4000);
				out.println("<mx>"+BestMX+"</mx>");
				out.println("<info>该域名的A记录指向有错</info>");
				out.println("<shortname>无具体邮箱信息</shortname>");
				EmailSystemShortName="无具体邮箱信息";
				
				//根据返回值判断邮件系统
				/*if(info!=""){
					EmailSystemShortName = outPut.getEmailSystemXML(info, "keyword", "abbr");
				}
				if(EmailSystemShortName.trim()=="0" || info.trim()==""){
					out.println("<info>该域名的A记录指向有错</info>");
					out.println("<shortname>无具体邮箱信息</shortname>");
					EmailSystemShortName="无具体邮箱信息";
				}else{
					out.println("<info>"+info+"</info>");
					out.println("<shortname>"+EmailSystemShortName+"</shortname>");
				}*/
			}
			String newStr = domain + "," + EmailSystemShortName;
			filein += newStr + "\r\n";
		}
		String b = CreateAndSaveFile(request, filein, tj, tran,addr);
		out.println("<address>" + b + "</address>");
		out.println("<tj>" + (tj + 1) + "</tj>");
		out.println("</response>");
		out.close();
		long endTime = System.currentTimeMillis();
		logger.info("Domains.150:" + domainLength + "条记录查询完毕。" + "本次查询用时:"
				+ (endTime - startTime) + "ms" + ",平均用时:"
				+ (endTime - startTime) / domainLength + "ms");
	}
	
	private String CreateAndSaveFile(HttpServletRequest request, String filein,
			int tj, int tran,String addr) {
		String filepath = "no file";
		String road = "download?pp=";
		System.out.println("第" + tj + "次请求，共" + tran + "次请求。");
		String txtname = "";
		//如果是第一次请求则生成文件
		if(tj==1){
			//生成文件
			Date date = new Date();
			SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH-mm");
			String nowtime = sf.format(date);
			Random random = new Random();
			int randomNum = Math.abs(random.nextInt()) % 1000;
			
			txtname = nowtime + "_" + String.valueOf(randomNum) + ".csv";
			HttpSession session = request.getSession();
			String path1 = session.getServletContext().getRealPath("/")
					+ "newfile";
			String path2 = session.getServletContext().getRealPath("/")
					+ "newfile/" + txtname;	
			File folder = new File(path1);
			if (!folder.exists()) {
				folder.mkdirs();
			}
			File file = new File(path2);
			try {
				file.createNewFile();
			} catch (IOException e) {
				e.printStackTrace();
			}
			RandomAccessFile mm = null;
			try {
				mm = new RandomAccessFile(file, "rw");
				mm.write(filein.getBytes("gb2312"));
			} catch (IOException e1) {
				logger.error("Domains.209:" + e1.getMessage());
			} finally {
				if (mm != null) {
					try {
						mm.close();
					} catch (IOException e2) {
						e2.printStackTrace();
						logger.error("Domains.216:" + e2.getMessage());
					}
				}
			}
			filepath = txtname;
		}
		if(tj==1 && tj==tran){
			filepath=road+txtname;
		}
		//如果是一次以后的请求则读文件并写入新内容,文件名从函数参数里面取
		else if (tj!=1 && tj<=tran) {
			//读写已生成的文件
			//System.out.println("读写已生成的文件");
			HttpSession session = request.getSession();
			String path01 = session.getServletContext().getRealPath("/")
					+ "newfile";
			String path02 = session.getServletContext().getRealPath("/")
					+ "newfile/" + addr;
			File file01=new File(path02);
			RandomAccessFile randomFile = null;
			try {
				randomFile = new RandomAccessFile(file01, "rw");
				long fileLength=randomFile.length();
				randomFile.seek(fileLength);
				randomFile.write(filein.getBytes("gb2312"));
			} catch (IOException e1) {
				logger.error("Domains.209:" + e1.getMessage());
			} finally {
				if (randomFile != null) {
					try {
						randomFile.close();
					} catch (IOException e2) {
						e2.printStackTrace();
						logger.error("Domains.216:" + e2.getMessage());
					}
				}
			}
			filepath= addr;
			//最后一次，把路径输入
			if(tj==tran){
				filepath=road+addr;
			}
		}
		return filepath;
	}
}
